/**
 * Created with IntelliJ IDEA.
 * User: osereda
 * Date: 02.06.13
 */
package com.google.code.bankagregator.common;

import com.google.code.bankagregator.entities.Currency;

import java.util.*;

/**
 * DetectCurrency name change to currency code.
 */
public class DetectCurrency {

    private final String EMPTY_STRING = "";
    private Map<Currency, ArrayList<String>> currencyMap;

    /**
     * Emulation of table with Key and Keywords fields.
     */
    private String[][] currencyPool =
            {
                    {Currency.UAH.toString(),
                            "грн,гривна,гривен"},
                    {Currency.USD.toString(),
                            "$,дол,доллары сша"},
                    {Currency.EUR.toString(),
                            "евро"},
                    {Currency.RUR.toString(),
                            "руб,рублей рф,российские рубли"}
            };

    public DetectCurrency() {
        currencyMap = new HashMap<>();
        for (Currency c : Currency.values()) {
            ArrayList<String> list = new ArrayList<>();
            list.add(c.toString());
            list.addAll(getKeywordsForCurrency(c));
            currencyMap.put(c, list);
        }
    }

    /**
     * Load keywords as List for specified currency. (Moc)
     *
     * @param currency specify currency.
     * @return List<string> with keywords.
     */
    public List<String> getKeywordsForCurrency(Currency currency) {
        for (String[] pool : currencyPool) {
            if (pool[0].equals(currency.toString())) {
                return Arrays.asList(pool[1].split(","));
            }
        }
        return new ArrayList<String>();
    }

    /**
     * Search for currency reference in specified string.
     *
     * @param string with reference to some currency.
     * @return currency abbreviation according to ENUM Currency for first reference
     *         or empty string if no reference found.
     */
    public String getCurrencyAbbreviation(String string) {
        String lowerCase = string.toLowerCase();

        for (Map.Entry<Currency, ArrayList<String>> entry : currencyMap.entrySet()) {
            for (String keyword : entry.getValue()) {
                if (lowerCase.contains(keyword)) {
                    return entry.getKey().toString();
                }
            }
        }
        return EMPTY_STRING;
    }

}
